<template>
  <div>
    <div class="input-group mt">
      <label>资料标题：</label>
      <div class="input-group-box"><el-input v-model="title" placeholder="在此输入资料标题（必须填写）"></el-input></div>
    </div>
    <div class="input-group mt">
      <label>资料简介：</label>
      <div class="input-group-box"><el-input v-model="note" type="textarea" :rows="5" placeholder="输入新闻简介（100字以内）"></el-input></div>
    </div>
    <div class="input-group">
      <label>封面图片：</label>
      <div class="input-group-box cover-box">
        <img :src="cover.url" class="cover" v-if="cover.url!==''">
        <div class="el-upload el-upload--picture-card">
          <i class="el-icon-plus"></i>
          <input type="file" id="cover-img" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" class="zi_upload_input" @change="getfile($event)">
        </div>
        <span class="p-tip">* 建议尺寸190*140</span>
      </div>
    </div>
    <div class="input-group mt">
      <label>下载需要登陆：</label>
      <el-select v-model="needAuth" placeholder="下载是否需要登陆" class="user-input">
        <el-option v-for="item in authOption"
                   :key="item.key"
                   :label="item.value"
                   :value="item.key">
        </el-option>
      </el-select>
    </div>
    <div class="input-group">
      <label>发布时间：</label>
      <div class="input-group-box">
        <el-date-picker
          v-model="repubTime"
          type="datetime"
          placeholder="请选择发布时间"
          format="yyyy-MM-dd HH:mm:ss"
          default-time="12:00:00">
        </el-date-picker>
      </div>
    </div>
    <div class="video" v-if="!showModifyVideo">
      <label>上传文件：</label>
      <div id="filePicker">选择文件</div>
      <div class="file-panel">
        <h2>文件上传区域</h2>
        <div class="file-list">
          <ul class="file-item" :class="`file-${file.id}`" v-for="file in fileList">
            <li class="file-type" :icon="fileCategory(file.ext)"></li>
            <li class="file-name">{{file.name}}</li>
            <li class="file-size">{{fileSize(file.size)}}</li>
            <li class="file-status">上传中...</li>
            <li class="file-operate">
              <!--   <a title="开始" @click="resume(file)"><i class="icon-sync"></i></a>
                 <a title="暂停" @click="stop(file)"><i class="icon-authority"></i></a>-->
              <a title="移除" @click="remove(file)"><i class="icon-delete"></i></a>
            </li>
            <li class="progress"></li>
          </ul>
          <div class="no-file" v-if="!fileList.length"><i class="iconfont icon-empty-file"></i> 暂无待上传文件</div>
        </div>
      </div>
      <vue-upload
        :accept="accept"
        :url="url"
        :formData="uploadFormData"
        :fileNumLimit="fileNumLimit"
        ref="uploader"
        uploadButton="#filePicker"
        :multiple="true"
        @beforeUpload="beforeUpload"
        @fileChange="fileChange"
        @progress="onProgress"
        @success="onSuccess"
      ></vue-upload>
    </div>
    <div class="video" style="margin-left: 40px;padding-top: 10px;" v-else>
      <el-button type="success" @click = 'showUploadFile'>重新上传文件</el-button>
    </div>

    <div class="bottom-box" v-if="isAdd">
      <el-button size="small" @click = 'saveAdd' :loading="saveAddLoading"> 保  存 </el-button>
    </div>
    <div class="bottom-box" v-else>
      <el-button size="small" @click = 'saveEditor' :loading="saveEditorLoading"> 保 存 修 改 </el-button>
    </div>
  </div>
</template>

<script>
  import apiConfig from '../../utils/apiconfig'
  import vueUpload from '../../components/upload'
  import api from '../../utils/api'
  import config from '../../utils/config'
  import WebUploader from '../../../static/lib/webuploader/webuploader.min.js'
  import $ from 'jquery'
  import helper from '../../utils/helper'
  export default {
    data () {
      return {
        title: '',
        newsDetail: '',
        note: '',
        cover: {
          url: '',
          img: ''
        },
        needAuth: 0,
        authOption: [
          {
            key: 1,
            value: '是',
          },
          {
            key: 0,
            value: '否',
          }
        ],
        isPublished: true,
        isAdd: true,
        publishLoading: false,
        saveAddLoading: false,
        showModifyVideo: false,
        repubTime: '',
        // 文件上传的参数
        fileList: [],
        url: '',
        uploadFormData: {
          md5: '',
          url: ''
        },
        fileNumLimit: 1, // 限制上传的个数
        accept: 'all',
        saveEditorLoading: false,
        loadPreview: false,
        accessKey: ''
      }
    },
    mounted () {

    },
    computed: {
      uploader () {
        return this.$refs.uploader
      }
    },
    created () {
      this.url = config.domain + helper.getManageApiUrl(apiConfig.uploadDownloadCenterFile)
      var id = this.$route.query.id

      if (id && id !== '' && id !== 'undefined' && id !== null) {
        this.aid = id
        this.isAdd = false
        this.getNewsDetail()
      } else {
        this.generateAccessKey()
      }
    },
    methods: {
      getfile (event) {
        this.cover.img = event.target.files[0]
        this.cover.url = window.URL.createObjectURL(this.cover.img)
      },
      saveArt (status) {
        let formData = new FormData()
        formData.append('title', this.title)
        formData.append('note', this.note)
        formData.append('need_auth', this.needAuth)
        formData.append('video_url', this.uploadFormData.url)
        formData.append('video_md5', this.uploadFormData.md5)
        formData.append('access_key', this.accessKey)
        formData.append('repub_time', helper.formatDateTime(this.repubTime))
        formData.append('img', this.cover.img)
        let configs = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        api.POST(helper.getManageApiUrl(apiConfig.addDownloadCenter), formData, configs, res => {
          var type = '保存'
          if (status === 1) {
            type = '发布'
          }
          this.$notify({
            title: '成功',
            message: type + '成功',
            type: 'success',
            duration: 1500
          })
          this.saveAddLoading = false
          this.title = ''
          this.note = ''
          this.uploadFormData.md5 = ''
          this.uploadFormData.url = ''
          this.repubTime = ''
          this.needAuth = 0
          var cover = document.getElementById('cover-img')
          cover.value = ''
          this.cover.url = ''
          this.fileList = []
        }, res => {
          this.saveAddLoading = false
          console.log(res)
        })
      },
      publish () {
        let note = this.note
        let title = this.title
        if (title.length === 0) {
          this.noEmpty('资料标题不能为空')
          return false
        }
        if (note.length === 0 || note.length > this.noteLimit) {
          this.noEmpty('资料简介不能为空且必须' + this.noteLimit + '字以内')
          return false
        }
        if (this.uploadFormData.md5 === '') {
          this.noEmpty('请上传文件')
          return false
        }
        this.publishLoading = true
        this.saveArt(1)
      },
      saveAdd () {
        let note = this.note
        let title = this.title
        if (title.length === 0) {
          this.noEmpty('资料标题不能为空')
          return false
        }
        if (note.length === 0 || note.length > this.noteLimit) {
          this.noEmpty('资料简介不能为空且必须' + this.noteLimit + '字以内')
          return false
        }
        if (this.uploadFormData.md5 === '') {
          this.noEmpty('请上传文件')
          return false
        }
        this.saveAddLoading = true
        this.saveArt(0)
      },
      saveEditor () {
        let note = this.note
        let title = this.title
        if (title.length === 0) {
          this.noEmpty('资料标题不能为空')
          return false
        }
        if (note.length === 0 || note.length > this.noteLimit) {
          this.noEmpty('资料简介不能为空且必须' + this.noteLimit + '字以内')
          return false
        }
        if (this.uploadFormData.md5 === '') {
          this.noEmpty('请上传文件')
          return false
        }
        this.saveEditorLoading = true
        let formData = new FormData()
        formData.append('id', this.aid)
        formData.append('title', this.title)
        formData.append('note', note)
        formData.append('need_auth', this.needAuth)
        formData.append('video_url', this.uploadFormData.url)
        formData.append('video_md5', this.uploadFormData.md5)
        formData.append('access_key', this.accessKey)
        formData.append('img', this.cover.img)
        formData.append('repub_time', helper.formatDateTime(this.repubTime))
        let configs = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        api.POST(helper.getManageApiUrl(apiConfig.updateDownloadCenter), formData, configs, res => {
          this.$notify({
            title: '成功',
            message: '修改已保存',
            type: 'success',
            duration: 1500
          })
          this.saveEditorLoading = false
          window.history.go(-1)
        }, res => {
          this.saveEditorLoading = false
          this.noEmpty(res.msg)
        })
      },
      showUploadFile () {
        this.showModifyVideo = !this.showModifyVideo
      },
      getNewsDetail () { // 修改新闻时，首先获取新闻内容
        this.loadPreview = true
        var param = {
          id: this.aid
        }
        api.GET(helper.getManageApiUrl(apiConfig.downloadCenterDetail), param, res => {
          var resData = res
          this.title = resData.title
          this.note = resData.note
          this.needAuth = resData.need_auth
          this.uploadFormData.md5 = resData.video_md5
          this.uploadFormData.url = resData.video_url
          this.accessKey = resData.access_key
          this.repubTime = resData.repub_time
          this.cover.url = resData.img
          this.cover.img = resData.img
          this.loadPreview = false
          this.showModifyVideo = true
        }, res => {
          this.noEmpty('获取数据失败')
        })
      },
      generateAccessKey () {
        console.log('access key =========>')
        let time = helper.getCurrentTime()
        this.accessKey = api.ENCRYPT(time)
        console.log('time key =========>' + time)
        console.log('access key =========>' + this.accessKey)
      },
      noEmpty (tip) {
        this.$notify({
          title: '提示',
          message: tip,
          type: 'error',
          duration: 1500
        })
      },
      getfile (event) {
        this.cover.img = event.target.files[0]
        this.cover.url = window.URL.createObjectURL(this.cover.img)
        console.log(this.cover.img)
      },
      fileChange (file) {
        console.log('正在计算MD5值...')
        if (!file.size) {
          return
        }
        this.fileList.push(file)
      },
      // 开始上传之前的事件，可以用于断点续传
      beforeUpload (block, data) {
      },

      onProgress (file, percent) {
        $(`.file-${file.id} .progress`).css('width', percent * 100 + '%')
        $(`.file-${file.id} .file-status`).html((percent * 100).toFixed(2) + '%')
      },
      onSuccess (file, response) {
        console.log('上传成功', response)
        let $fileStatus = $(`.file-${file.id} .file-status`)
        $fileStatus.html('上传成功，转码中')
        if (response.errcode === 200) {
          let md5 = response.data.md5
          let fileType = response.data.type
          let param = {
            'md5': md5,
            'file_name': file.name,
            'file_type': fileType,
            'access_key': this.accessKey
          }
          this.uploadFormData.md5 = md5
          this.uploadFormData.url = md5 + '.' + fileType
          api.GET(helper.getManageApiUrl(apiConfig.mergeDownloadCenterFile), param, res => {
            console.log('上传结果', res)
            if (res.status === 200) {
              $fileStatus.html('上传成功，转码中')
            } else if (res.status === 1) {
              $fileStatus.html('上传失败')
            } else if (res.status === 2) {
              $fileStatus.html('上传成功')
              file.fid = res.fid
              console.log(file)
            }
          }, res => {
            console.log(res)
          })
        }
      },

      uploadError (file, reason) {
        this.uploader.retry(file)
      },

      resume (file) {
        this.uploader.upload(file)
      },
      stop (file) {
        this.uploader.stop(file)
      },
      remove (file) {
        // 取消并中断文件上传
        this.uploader.cancelFile(file)
        // 在队列中移除文件
        this.uploader.removeFile(file, true)
        if (file !== 'undefined' && file.fid > 0) {
          let fid = file.fid
          let param = {
            'id': fid
          }
          this.loadPreview = true
          api.GET(helper.getManageApiUrl(apiConfig.deleteAttach), param, res => {
            // 在ui上移除
            let index = this.fileList.findIndex(ele => ele.id === file.id)
            this.fileList.splice(index, 1)
            this.loadPreview = false
          })
        }
      },

      fileSize (size) {
        return WebUploader.Base.formatSize(size)
      },
      fileCategory (ext) {
        let type = ''

        const typeMap = {
          image: ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp'],
          video: ['mp4', 'm3u8', 'rmvb', 'avi', 'swf', '3gp', 'mkv', 'flv'],
          text: ['doc', 'txt', 'docx', 'pages', 'epub', 'pdf', 'numbers', 'csv', 'xls', 'xlsx', 'keynote', 'ppt', 'pptx']
        }

        Object.keys(typeMap).forEach((_type) => {
          const extensions = typeMap[_type]
          if (extensions.indexOf(ext) > -1) {
            type = _type
          }
        })
        return type
      }
    },
    watch: {},
    components: {
      vueUpload
    }
  }
</script>

<style>
  .art-fade {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 99;
    background: rgba(255, 255, 255, 0.7);
    padding-top: 5%;
  }
  .input-group-box .el-upload--picture-card {
    position: relative;
    width: 100px;
    height: 100px;
  }
  .input-group-box img.cover {
    width: 95px;
    height: 71px;
    display: block;
    margin-bottom: 10px;
  }
  .input-group-box .el-upload--picture-card i {
    position: absolute;
    top: 35px;
    left: 35px;
  }
  .el-upload--picture-card .zi_upload_input {
    position: absolute;
    display: inline-block;
    width: 100%;
    height: 100%;
    opacity: 0;
    top: 0;
    left: 0;
    cursor: pointer;
  }
  .input-group .input-group-box label.el-switch {
    width: auto;
    line-height: auto;
    margin-top: 7px;
    vertical-align: top
  }
  .art-title-box {
    margin-bottom: 8px;
    padding: 0px 25px;
  }
  .art-title{
    width: 100%;
    border: none;
    background-color: transparent;
    color: #000;
    font-size: 22px;
    height: 45px;
    line-height: 45px;
  }
  .input-group.mt {
    margin-top: 24px;
  }
  .bottom-box {
    position: fixed;
    bottom: 0;
    box-sizing: border-box;
    width: 100%;
    left: 180px;
    background: #f2f2f2;
    border-top: 1px solid #dedede;
    height: 50px;
    text-align: right;
    line-height: 50px;
    padding-right: 350px;
  }
  .bottom-box .el-button {
    margin-left: 25px;
  }
  .cover-box .p-tip {
    display: inline-block;
    color: red;
    font-size: 12px;
    margin-top: 80px;
    margin-left: 10px;
  }

  .video label{
    display: inline-block;
    flex: 0 0 100px;
    width: 100px;
    text-align: right;
    font-size: 14px;
    color: #999;
    line-height: 36px;
    padding-right: 15px;
  }
  #filePicker {
    margin-left: 100px;
  }
  .file-panel {
    width: 90%;
    margin-top: 10px;
    margin-left: 100px;
    margin-bottom: 20px;
    height: 300px;
    box-shadow: 0 2px 12px 1px rgba(0, 0, 0, 0.1);
  }
  .file-panel h2 {
    height: 40px;
    line-height: 40px;
    padding: 0 10px;
    border-radius: 4px 4px 0 0;
    border-bottom: 1px solid #ccc;
    background-color: #fff;
  }

  .file-panel .file-list {
    position: relative;
    height: 260px;
    overflow-y: auto;
    background-color: rgb(250, 250, 250);
  }

  .file-panel  .file-item {
    position: relative;
    height: 50px;
    line-height: 50px;
    padding: 0 10px;
    border-bottom: 1px solid #ccc;
    background-color: #fff;
    z-index: 1
  }

  .file-panel  .file-item li {
    display: inline-block;
  }
  .file-panel  .file-type {
    width: 24px;
    height: 24px;
    vertical-align: -5px;
  }
  .file-panel  .file-name {
    width: 40%;
    margin-left: 10px;
  }
  .file-panel  .file-size {
    width: 20%;
  }
  .file-panel .file-status {
    width: 20%;
  }
  .file-panel .file-operate {
    width: 10%;
  }
  .file-panel .file-operate a {
    padding: 10px 5px;
    cursor: pointer;
    color: #666;
  }
  .file-panel .file-operate a:hover {
    color: #ff4081;
  }
  .file-panel  .file-type[icon=text] {
    background: url(../../../src/img/icon/icon-text.png);
  }
  .file-panel .file-type[icon=video] {
    background: url(../../../src/img/icon/icon-video.png);
  }
  .file-panel .file-type[icon=image] {
    background: url(../../../src/img/icon/icon-img.png);
  }

  .file-panel .progress {
    position: absolute;
    top: 0;
    left: 0;
    height: 49px;
    width: 0;
    background-color: #E2EDFE;
    z-index: -1;
  }

  .file-panel .no-file {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 16px;
  }
</style>
